from custom.handlers.basehandler import BaseRequestHandler
from utils.wechat import check_wx_signature, parse_wx_msg, receive, replay
from utils.wechat.kf_replay import KfTextMessage, KfMusicMessage, KfNewsMessage
from utils.qq_music import get_song_key, query_music, download_file, get_album_thumb
from settings.config import config
from models.tables import MusicModel
from utils.tuling import get_tl_replay
from sqlalchemy.exc import OperationalError
import requests
import os
import json
import time
from requests import urllib3
urllib3.disable_warnings()


class WechatHandler(BaseRequestHandler):

    event_map = {}

    def get(self, *args, **kwargs):
        timestamp = self.get_argument('timestamp', '')
        nonce = self.get_argument('nonce', '')
        signature = self.get_argument('signature', '')
        echostr = self.get_argument('echostr', '')
        if check_wx_signature(config.WeChatConfig.Token, timestamp, nonce, signature):
            print(1)
            self.write(echostr)
        else:
            print(2)
            self.write('error')

    def post(self, *args, **kwargs):
        rec_msg = parse_wx_msg(self.request.body)

        if isinstance(rec_msg, receive.EventMessage):
            from_user = rec_msg.FromUserName
            self.event_map[from_user] = rec_msg.EventKey
            text = ''
            if rec_msg.EventKey == config.WeChatConfig.Menus.get('music', dict()).get('key', ''):
                text = '输入你想听的音乐吧！'
            if rec_msg.EventKey == config.WeChatConfig.Menus.get('chat', dict()).get('key', ''):
                text = '来开始聊天吧！'
            if text:
                kf_replay_msg = KfTextMessage(from_user, text)
                self.wx_token_manager.send_kf_msg(kf_replay_msg.to_json())
            self.write('')
            return
        elif isinstance(rec_msg, receive.TextMessage):
            self.write('')
            from_user = rec_msg.FromUserName
            current_event_key = self.event_map.get(from_user, '')
            if not current_event_key:
                kf_replay_msg = KfTextMessage(from_user, '请点击菜单选择你想要的服务...')
                self.wx_token_manager.send_kf_msg(kf_replay_msg.to_json())
                return
            if current_event_key == config.WeChatConfig.Menus.get('music', dict()).get('key', ''):
                self.do_music_action(rec_msg)
            if current_event_key == config.WeChatConfig.Menus.get('chat', dict()).get('key', ''):
                self.do_chat_action(rec_msg)

        elif isinstance(rec_msg, receive.ImageMessage):
            to_user = rec_msg.FromUserName
            from_user = rec_msg.ToUserName
            media = rec_msg.MediaId
            replay_msg = replay.ImageMessage(to_user=to_user, from_user=from_user, media_id=media)
            self.write(replay_msg.send())
        elif isinstance(rec_msg, receive.VoiceMessage):
            to_user = rec_msg.FromUserName
            from_user = rec_msg.ToUserName
            media_id = 'N1oQMwupTlRuKRzyIj70e7-SfYQtMnMqXn0pyx3ElWE'
            replay_msg = replay.VoiceMessage(to_user=to_user, from_user=from_user, media_id=media_id)
            self.write(replay_msg.send())
        else:
            to_user = rec_msg.FromUserName
            from_user = rec_msg.ToUserName
            content = '我不知道你发的是什么...'
            replay_msg = replay.TextMessage(to_user=to_user, from_user=from_user, content=content)
            self.write(replay_msg.send())

    def handle_query_result(self, result_list, keyword):
        db_result = list()
        if len(result_list) == 0:
            return db_result
        for _ in result_list:
            song_mid = _.get('song_mid', '')
            album_mid = _.get('album_id', '')
            db_song = self.db.query(MusicModel).filter_by(song_mid=song_mid).first()
            need_commit = False
            if db_song:
                db_result.append({
                    "title": db_song.song_name + '-' + db_song.singer_name,
                    "description": db_song.song_desc or db_song.song_name,
                    "url": config.DOMAIN + 'music/index?song_mid=' + song_mid,
                    "picurl": config.DOMAIN + db_song.my_thumb_url
                })
            else:
                need_commit = True
                thumb_url = get_album_thumb(album_mid)
                thumb_file = download_file('image', thumb_url)
                music = MusicModel(keyword=keyword,
                                   song_id=_.get('song_id', ''),
                                   song_name=_.get('song_name', ''),
                                   song_desc=_.get('song_desc', ''),
                                   singer_name=_.get('singer_name', ''),
                                   song_mid=_.get('song_mid', ''),
                                   album_id=_.get('album_id', ''),
                                   song_url='',
                                   my_song_url='',
                                   thumb_url=thumb_url,
                                   my_thumb_url=thumb_file.get('server_path'),
                                   thumb_media_id='',
                                   thumb_time=str(int(time.time())))
                self.db.add(music)
                db_result.append({
                    "title": _.get('song_name', '') + '-' + _.get('singer_name', ''),
                    "description": _.get('song_desc', '') or _.get('song_name', ''),
                    "url": config.DOMAIN + 'music/index?song_mid=' + song_mid,
                    "picurl": config.DOMAIN + thumb_file.get('server_path')
                })
        if need_commit:
            self.db.commit()
        return db_result

    def do_chat_action(self, rec_msg):
        from_user = rec_msg.FromUserName
        keyword = rec_msg.Content
        replay_text = get_tl_replay(keyword)
        kf_replay_msg = KfTextMessage(from_user, replay_text)
        self.wx_token_manager.send_kf_msg(kf_replay_msg.to_json())

    def do_music_action(self, rec_msg):
        from_user = rec_msg.FromUserName
        result = query_music(rec_msg.Content)
        keyword = rec_msg.Content
        db_result = self.handle_query_result(result, keyword)
        if len(db_result) == 0:
            kf_replay_msg = KfTextMessage(from_user, '我找不到你想要的，555')
            self.wx_token_manager.send_kf_msg(kf_replay_msg.to_json())
            return
        news_info = {
            'articles': db_result
        }
        print(db_result)
        kf_replay_msg = KfNewsMessage(from_user, news_info)
        # kf_replay_msg = KfMusicMessage(from_user, music_info)
        self.wx_token_manager.send_kf_msg(kf_replay_msg.to_json())